package com.btl.cygf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.btl.zujian.SelectPicPopup;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class FaTie extends Activity implements OnClickListener {

	private ImageView login_backtofragment;
	private TextView fabu;
	private EditText tiezi_name;
	private EditText tiezi_jianjie;
	private EditText tiezi_cailiao;
	private Spinner tiezi_sort;
	private TextView plus_bu;
	private LinearLayout buzou_out;
	private ImageView zhanshi;
	private TextView zhanshi_id;

	private SelectPicPopup spp;

	private File file;
	private String filename;
	private int code;
	private boolean flag;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.fabu_tiezi);
		initView();
	}

	private void initView() {
		login_backtofragment = (ImageView) findViewById(R.id.login_backtofragment);
		fabu = (TextView) findViewById(R.id.fabu);
		plus_bu = (TextView) findViewById(R.id.plus_bu);
		tiezi_jianjie = (EditText) findViewById(R.id.tiezi_jianjie);
		tiezi_name = (EditText) findViewById(R.id.tiezi_name);
		tiezi_cailiao = (EditText) findViewById(R.id.tiezi_cailiao);
		tiezi_sort = (Spinner) findViewById(R.id.tiezi_sort);
		buzou_out = (LinearLayout) findViewById(R.id.buzou_out);

		zhanshi = (ImageView) findViewById(R.id.zhanshi);
		zhanshi_id = (TextView) findViewById(R.id.zhanshi_id);

		login_backtofragment.setFocusable(true);
		login_backtofragment.setFocusableInTouchMode(true);
		login_backtofragment.requestFocus(); // 初始不让EditText得焦点
		login_backtofragment.requestFocusFromTouch();

		login_backtofragment.setOnClickListener(this);
		fabu.setOnClickListener(this);
		plus_bu.setOnClickListener(this);
		tiezi_jianjie.setOnClickListener(this);
		tiezi_name.setOnClickListener(this);
		tiezi_cailiao.setOnClickListener(this);
		zhanshi.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();

		switch (id) {
		case R.id.login_backtofragment:
			finish();
			break;

		case R.id.zhanshi:
			code = 150;
			getImage();
			break;
		case R.id.fabu:
			try {
				if(!flag) {
					flag = true;
					fabu();
					
				}
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.plus_bu:
			plusBu();
			break;

		}

		if (id >= 1000 && id < 2000) {
			// 点的是选择图片
			code = id -1000;
			getImage();
			
		} else if (id >= 4000 && id < 5000) {
			// 点的是删除图片
			if (buzou_out.getChildCount() > 0) {
				View view = buzou_out.findViewById(id - 4000);
				buzou_out.removeView(view);
			}
		}

	}

	private void getImage() {

		spp = new SelectPicPopup(FaTie.this, itemsOnClick);
		spp.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM
				| Gravity.CENTER_HORIZONTAL, 0, 0);

	}

	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			spp.dismiss();
			switch (v.getId()) {
			case R.id.btn_take_photo:// 拍照
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					String saveDir = Environment.getExternalStorageDirectory()
							+ "/btl";
					File dir = new File(saveDir);
					if (!dir.exists()) {
						dir.mkdir();
					}
					filename = System.currentTimeMillis() + ".jpg";
					file = new File(saveDir, filename);
					file.delete();
					if (!file.exists()) {
						try {
							file.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
							return;
						}
					}
				}
				System.out.println(code + "requestCode");
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(file));
				startActivityForResult(intent, 101);

				break;
			case R.id.btn_pick_photo:// 选取相册
				System.out.println(code);
				Intent intent1 = new Intent(Intent.ACTION_PICK, null);
				intent1.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
				startActivityForResult(intent1, 200);

				break;
			default:
				break;
			}

		}

	};

	private void fabu() throws FileNotFoundException {

		if (tiezi_name.getText().toString().equals("")) {
			Toast.makeText(getApplicationContext(), "帖子标题不能为空", 1).show();
			flag = false;

		} else {
			AsyncHttpClient client = new AsyncHttpClient();
			RequestParams params = new RequestParams();

			params.add("title", tiezi_name.getText().toString());
			params.add("jianjie", tiezi_jianjie.getText().toString());
			params.add("cailiao", tiezi_cailiao.getText().toString());
			params.add("sort", tiezi_sort.getSelectedItem().toString());
			if (zhanshi_id.getText().toString().equals("")) {
				Toast.makeText(this, "展示图片不能为空", 1).show();
				flag = false;
				return;
			} else {
				params.put("zhanshi", new File(zhanshi_id.getText().toString()));

			}

			for (int i = 0; i < buzou_out.getChildCount(); i++) {

				LinearLayout addItem = (LinearLayout) buzou_out.getChildAt(i);
				TextView tv = (TextView) addItem.getChildAt(1);
				EditText et = (EditText) addItem.getChildAt(2);
				System.out.println(tv.getText().toString() + " ; "
						+ et.getText().toString());

				if (!tv.getText().toString().equals("")) {

					params.put("buzuotu" + i, new File(tv.getText().toString()));
				}

				if (et.getText().toString().equals("")) {
					Toast.makeText(this, "步骤内容不能为空", 1).show();
					return;
				} else {
					params.put("buzuContent" + i, et.getText().toString());
				}

			}
			params.put("buzushu", buzou_out.getChildCount() + "");
			SharedPreferences share = getSharedPreferences("login",
					Activity.MODE_WORLD_READABLE);

			String id = share.getString("id", "");
			params.add("id", id);
			client.post(getResources().getString(R.string.url)
					+ "/CYGF/fabu.tiezi", params,
					new JsonHttpResponseHandler() {
						// 链接成功做出的反应
						@Override
						public void onSuccess(int statusCode, Header[] headers,
								JSONArray response) {
							JSONObject object1 = response.optJSONObject(1);
							JSONObject object = response.optJSONObject(0);
							String result = object.optString("msg");
							Toast.makeText(FaTie.this, result, 1).show();
							super.onSuccess(statusCode, headers, response);

							Intent it = new Intent();
							it.setClass(FaTie.this, MainActivity.class);
							it.putExtra("type", 1);
							it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(it);
						}

						// 链接网络失败，做出的反应
						@Override
						public void onFailure(int statusCode, Header[] headers,
								Throwable throwable, JSONArray errorResponse) {
							super.onFailure(statusCode, headers, throwable,
									errorResponse);
						}
					});
		}

	}

	private void plusBu() {
		int num = buzou_out.getChildCount();
		System.out.println("点击添加按钮时：" + num);
		LinearLayout addItem = (LinearLayout) LayoutInflater.from(this)
				.inflate(R.layout.buzou_item1, null);
		buzou_out.addView(addItem);

		ImageView iv0 = (ImageView) addItem.getChildAt(0); // 图片
		View view1 = addItem.getChildAt(1); // 图片地址
		View view2 = addItem.getChildAt(2); // 步骤内容
		View view3 = addItem.getChildAt(3); // 删除

		iv0.setId(1000 + num);
		view1.setId(2000 + num); // url EditText
		view2.setId(3000 + num); //
		view3.setId(4000 + num); // 删除
		addItem.setId(num);
		iv0.setOnClickListener(this);
		view3.setOnClickListener(this);

	}

	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		System.out.println(requestCode);
		String path = null;

		switch (requestCode) {
		case 101:

			path = Environment.getExternalStorageDirectory() + "/btl/"
					+ filename;
			requestCode = code;
			break;

		default:

			if (resultCode == Activity.RESULT_OK) {
				if (data != null && data.getData() != null) {
					// 根据返回的URI获取对应的SQLite信息
					Uri uri = data.getData();

					final String[] proj = { MediaStore.Images.Media.DATA };
					Cursor cursor = null;
					try {
						cursor = this.getContentResolver().query(uri, proj,
								null, null, null);
						int column_index = cursor
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
						cursor.moveToFirst();
						path = cursor.getString(column_index);
					} finally {
						if (cursor != null) {
							cursor.close();
							cursor = null;
						}
					}
				}
			}
			
			requestCode = code;
			break;
		}

		if (path != null && requestCode > 100) {
			System.out.println(path);
			zhanshi_id.setText(path);
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 4;
			zhanshi.setImageBitmap(BitmapFactory.decodeFile(path, options));
		}

		else if (path != null ) {
			// 这里很奇葩的方式, 将获取到的值赋值给相应的EditText, 竟然能对应上
			TextView editText = (TextView) buzou_out
					.findViewById(requestCode + 2000);
			editText.setText(path);
			System.out.println(path);
			System.out.println(editText);
			ImageView iv = (ImageView) buzou_out
					.findViewById(requestCode + 1000);

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 4;
			iv.setImageBitmap(BitmapFactory.decodeFile(path, options));
		
		} else {

			showToast("请重新选择图片");
		}

	}

	Toast mToast = null;

	private void showToast(String text) {
		if (mToast != null && !super.isFinishing()) {
			mToast.setText(text);
			mToast.show();
			return;
		}
		mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
		mToast.show();
	}

}
